import {nanoid} from "nanoid";
import {EventsEmit, EventsOnce} from "frontend/src/wailsjs/runtime";

export interface Response<T = any> {
    Data: T,
    Error: string
}

export interface Request<T = any> {
    channel: string
    type: string
    payload?: T
}

const event = "dialog"

export enum Mode {
    File = "file",
    Files = "files",
    Dir = "dir",
    Save="save",
    Message="message"
}

export interface FileFilterOption {
    displayName: string
    Pattern: string
}

export interface FileDialogOption {
    title?: string
    defaultFilename?: string
    defaultDirectory?: string
    showHiddenFiles?: boolean,
    filters?: FileFilterOption[]
}

export type DialogOption = {
    [P in string]: unknown
} & FileDialogOption

export function Dialog(type:Mode,option:DialogOption){
    return new Promise((resolve,reject) => {
        let channel = nanoid()
        EventsOnce(channel,(data:Response)=>{
            if(data.Error){
                reject(data.Error)
            } else {
                resolve(data.Data)
            }
        })

        EventsEmit(event,JSON.stringify(<Request<DialogOption>>{
            channel: channel,
            type: type,
            payload: option
        }))
    })
}

(window as any).dialog = Dialog